package com.aitaoxue.palx.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.InjectView;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.adapter.SortAdapter;
import com.aitaoxue.palx.base.BaseActivity;
import com.aitaoxue.palx.bean.SortModel;
import com.aitaoxue.palx.db.InfoDBHelper;
import com.aitaoxue.palx.util.CharacterParser;
import com.aitaoxue.palx.util.StringUtils;
import com.aitaoxue.palx.widget.ClearEditText;
import com.aitaoxue.palx.widget.SideBar;
import com.aitaoxue.palx.widget.SideBar.OnTouchingLetterChangedListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class CityChooseAvtivity extends BaseActivity {

	@InjectView(R.id.country_lv)
	protected ListView sortListView;

	@InjectView(R.id.sidebar)
	protected SideBar sideBar;

	@InjectView(R.id.dialog)
	protected TextView dialog;

	private SortAdapter adapter;

	@InjectView(R.id.filter_edit)
	protected ClearEditText mClearEditText;

	private CharacterParser characterParser;
	private List<SortModel> sourceDateList;

	private LocationClient mLocationClient = null;
	private BDLocationListener myListener = new MyLocationListener();

	HashMap<String, Integer> map = null;

	@Override
	public void onClick(View arg0) {

	}

	@Override
	public void initView() {
		characterParser = CharacterParser.getInstance();

		sideBar.setTextView(dialog);

	}

	@Override
	public void initData() {
		// 城市数据列表
		// 没有阻塞,可以不用asynctask
		map = InfoDBHelper.getAllCitys();
		ArrayList<String> datas = new ArrayList<String>();
		datas.addAll(map.keySet());
		sourceDateList = filledData(datas);

		Collections.sort(sourceDateList);
		adapter = new SortAdapter(this, sourceDateList);

		sortListView.setAdapter(adapter);

		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub

			}
		});

		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}
			}
		});

		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent();
				final String city = ((SortModel) adapter.getItem(position))
						.getName();
				if (city.startsWith("定位")) {
					intent.putExtra("selected_city", "");
				} else {

					AppContext.getInstance().setProperties(new Properties() {
						{
							setProperty("user.city", city);
							setProperty("user.cityid",
									String.valueOf(map.get(city)));
						}
					});

					intent.putExtra("selected_city", city);
				}

				setResult(RESULT_OK, intent);
				finish();
			}
		});

		initLocation();
	}

	@Override
	protected int getLayoutId() {
		return R.layout.city_choose;
	}

	@Override
	protected boolean hasBackButton() {
		return true;
	}

	@Override
	protected int getActionBarTitle() {
		return R.string.choose_city;
	}

	private void initLocation() {

		mLocationClient = new LocationClient(AppContext.getInstance());
		mLocationClient.registerLocationListener(myListener);

		LocationClientOption option = new LocationClientOption();
		option.setCoorType("bd09ll");
		option.setOpenGps(true);
		option.setIsNeedAddress(true);

		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}

	private List<SortModel> filledData(ArrayList<String> datas) {
		List<SortModel> mSortList = new ArrayList<SortModel>();

		for (String data : datas) {
			SortModel sortModel = new SortModel();
			sortModel.setName(data);

			String pinyin = characterParser.getSelling(data);
			String sortString = pinyin.substring(0, 1).toUpperCase();

			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}

			mSortList.add(sortModel);
		}

		mSortList.add(new SortModel("定位中...", "@"));
		mSortList.add(new SortModel("西安市", "!"));
		mSortList.add(new SortModel("成都市", "!"));

		return mSortList;
	}

	private void filterData(String filterStr) {
		List<SortModel> filterDataList = new ArrayList<SortModel>();

		if (StringUtils.isEmpty(filterStr)) {
			filterDataList = sourceDateList;
		} else {
			filterDataList.clear();
			for (SortModel sortModel : sourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDataList.add(sortModel);
				}
			}
		}

		Collections.sort(filterDataList);
		adapter.updateListView(filterDataList);
	}

	private class MyLocationListener implements BDLocationListener {

		@SuppressWarnings("serial")
		@Override
		public void onReceiveLocation(BDLocation location) {
			final String city = location.getCity();
			final double latitude = location.getLatitude();
			final double longitude = location.getLongitude();

			// 关闭定位
			mLocationClient.stop();

			// 保存城市和经纬度
			AppContext.getInstance().setProperties(new Properties() {
				{
					// setProperty("user.city", city);
					setProperty("user.latitude", String.valueOf(latitude));
					setProperty("user.longitude", String.valueOf(longitude));
				}
			});

			updateLocation(city);
		}
	}

	@Override
	protected void onStop() {
		mLocationClient.stop();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		mLocationClient = null;
		myListener = null;
		super.onDestroy();
	}

	private void updateLocation(String city) {
		if (city == null) {
			sourceDateList.get(0).setName("定位失败");
		} else {
			sourceDateList.get(0).setName(city);
		}

		adapter.updateListView(sourceDateList);
	}
}
